﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sora.Data.Models;
using Sora.Data;

namespace Sora.HelpSystem.Package.Pages
{
    public class HelpPagesRepository : TreeObject<HelpPage>
    {
        public HelpDocument Document { get; private set; }

        private Dictionary<IEntry, HelpPage> Cache { get; set; }
        
        public HelpPagesRepository(HelpDocument document, IEntry key)
            : base(key)
        {
            if (document == null)
                throw new ArgumentNullException("document");

            Document = document;
        }

        internal bool IsRootKey(HelpPage page)
        {
            if (page == null)
                return false;
            else
            {
                return RootKey.Equals(page.InternalKey);
            }
        }

        internal HelpPage LoadInternalObject(IEntry key)
        {
            return LoadObject(key);
        }

        protected override HelpPage LoadObject(IEntry key)
        {
            if(Cache == null)
            {
                Cache = new Dictionary<IEntry,HelpPage>();
            }
            
            IEntry[] keys = new IEntry[Cache.Keys.Count];
            Cache.Keys.CopyTo(keys, 0);
            
            foreach (var old_key in keys)
            {
                if (old_key.Deleted)
                    Cache.Remove(old_key);
            }

            HelpPage result = null;

            if (!Cache.TryGetValue(key, out result))
            {
                result = Cache[key] = new HelpPage(this, key);
            }

            return result;
        }
    }
}
